﻿#include "MyWindow.h"
#include <sstream>
#include "MyUtils.h"

const std::string _sClassName = "MyWindow";
static MyWindow* _sMyWindow = nullptr;

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	return _sMyWindow->HandleMsg(hwnd, msg, wParam, lParam);
}

LRESULT MyWindow::HandleMsg(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	//OutputDebugString("====> handleMsg called!");
	switch (msg)
	{
	case WM_CLOSE:
		PostQuitMessage(0);
		break;

	case WM_KILLFOCUS:
		// 窗口失去焦点
		break;

	case WM_KEYDOWN:
	case WM_SYSKEYDOWN:
		// keydown
	{

	}
	break;

	case WM_KEYUP:
	case WM_SYSKEYUP:
		// keyup
		break;
	case WM_MOUSEMOVE:
		// 鼠标移动
		break;
	case WM_LBUTTONDOWN:
		// left mouse button down
	{
		POINTS pt = MAKEPOINTS(lParam);
		std::ostringstream oss;
		oss << "(" << pt.x << "," << pt.y << ")";
		SetWindowText(_hWnd, oss.str().c_str());
	}
	break;
	case WM_LBUTTONUP:
		// left mouse button up
		break;

	case WM_RBUTTONDOWN:
		// right mouse button down
		break;
	case WM_RBUTTONUP:
		// right mouse button up
		break;
	case WM_MOUSEWHEEL:
		// 鼠标滚轮

		break;
	default:
		break;
	}
	return DefWindowProc(hwnd, msg, wParam, lParam);
}

MyWindow::MyWindow(int width, int height, const std::string & title) :
	_width(width),
	_height(height),
	_title(title)
{
	_sMyWindow = this;
	_hInstance = MY_CHECK_NULL(GetModuleHandle(nullptr));
}

void MyWindow::Init()
{
	// 注册窗口
	// register window class
	WNDCLASSEX wc = { 0 };
	wc.cbSize = sizeof(wc);
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = _hInstance;
	wc.hIcon = nullptr;
	wc.hCursor = nullptr;
	wc.hbrBackground = nullptr;
	wc.lpszMenuName = nullptr;
	wc.lpszClassName = _sClassName.c_str();
	wc.hIconSm = nullptr;
	RegisterClassEx(&wc);

	//----------------
	DWORD windowStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;
	BOOL hasMenu = false;

	RECT rect;
	rect.left = rect.top = 100;
	rect.right = rect.left + _width;
	rect.bottom = rect.top + _height;
	MY_CHECK_NULL(AdjustWindowRect(&rect, windowStyle, hasMenu));

	// create window instance
	_hWnd = MY_CHECK_NULL(CreateWindowEx(
		0,
		_sClassName.c_str(),
		_title.c_str(),
		windowStyle,
		rect.left,
		rect.top,
		rect.right - rect.left,
		rect.bottom - rect.top,
		nullptr,
		nullptr,
		_hInstance,
		nullptr
	));
	ShowWindow(_hWnd, SW_SHOWDEFAULT);

	m_Graphics = std::make_unique<Graphics>(_hWnd);
}

Graphics & MyWindow::GetGraphics()
{
	MY_ASSET(m_Graphics != nullptr, "graphics is null!");
	return *m_Graphics;
}

MyWindow::~MyWindow()
{
	UnregisterClass(_sClassName.c_str(), _hInstance);
}